/*
 * @Author: Huangdong
 * @Date: 2022-03-29 16:49:35
 * @LastEditors: minsheng_insurance_agency_zhoucl
 * @LastEditTime: 2025-11-27 15:54:19
 * @FilePath: \01.latest-short-insure\src\mixins\userInfo.js
 * @Description:
 *
 *
 */
import { mapGetters } from "vuex";
import { countYearDayForAge, dateToString } from "@/methods/date.js";
import { tellPhoneFormat, idNumFormat } from "@/methods/format.js";
import {
  idNumCheck,
  emailCheck,
  addrCheck,
} from "@/translate/validate/customer";
import { nameRuleCheck } from "@/translate/validate/fields.js";
import { checkPhoneSmsCode } from "@/methods/apis.js";
export const userInfoMix = {
  data() {
    return {
      userInfo: {
        relationToAppnt: "",
        name: "", // "姓名",
        idType: "", // "证件类型",
        idNum: "", //"证件号",
        validDate: "", //"证件有效期起期",
        validDateEnd: "", //"证件有效期止期",
        sex: "", //"性别",
        birthDate: "", // "出生日期",
        age: "", //"年龄",
        phone: "", //"手机号",
        email: "", //"邮箱",
        crsIdType: "", //"税收居民身份类型",
        crsIdTypeName: "",
        socialInsuFlag: "", // "社保标识",
        occupationCode: "", // "职业编号",
        occupationClass: "",
        occupationCodeName: "",
        // 现居地址
        province: "", //"省份编码",
        provinceName: "", //" 省份名称",
        city: "", //" 市编码",
        cityName: "", //" 市名称",
        county: "", //" 区县编码",
        countyName: "", //" 区县名称",
        town: "", //" 乡镇街道编码",
        townName: "", //" 乡镇街道名称",
        areaName: "", //" 地区名称（省份名称+市名称+区县名称）",
        permanentAddress: "", // " 详细地址",
        nationality: "", // 国籍
        nationalityName: "",
        income: "", //收入
        height: "",
        weight: "",
        healthyStatus: "",
        frontImg: "",
        backImg: "",
        uwMedicalId: "", // 智能核保返回标识
      },
      tipsInfo: {
        name: "", // "姓名",
        idType: "", // "证件类型",
        idNum: "", //"证件号",
        validDate: "", //"证件有效期起期",
        validDateEnd: "", //"证件有效期止期",
        sex: "", //"性别",
        birthDate: "", // "出生日期",
        age: "", //"年龄",
        phone: "", //"手机号",
        email: "", //"邮箱",
        crsIdType: "", //"税收居民身份类型",
        socialInsuFlag: "", // "社保标识",
        incomeLevel: "", //"收入",
        occupationCode: "", // "职业编号",
        province: "", //"家庭住址 省份编码",
        provinceName: "", //"家庭住址 省份名称",
        city: "", //"家庭住址 市编码",
        cityName: "", //"家庭住址 市名称",
        county: "", //"家庭住址 区县编码",
        countyName: "", //"家庭住址 区县名称",
        town: "", //"家庭住址 乡镇街道编码",
        townName: "", //"家庭住址 乡镇街道名称",
        areaName: "", //"家庭住址 地区名称（省份名称+市名称+区县名称）",
        permanentAddress: "", // "家庭住址 详细地址",
        frontImg: "",
        backImg: "",
        income: "",
        height: "",
        weight: "",
        nationality: "",
        healthyStatus: "",
        relationToAppnt: "",
      },
      defaultIndex: 0,
      showFile: false,
      pageLoad: false, //页面已加载
      showEmailAppend: false, //邮箱后缀自动补全
      showPop: false,
      showUserList: false,
      validDateDisabled: false,
      refname: "",
      refidNum: "",
      refidType: "",
      refvalidDate: "",
      refvalidDateEnd: "",
      refemail: "",
      refphone: "",
      refzipCode: "",
      refpermanentAddress: "",
      refsocialInsuFlag: "",
      refcrsIdType: "",
      refincomeLevel: "",
      refgrpName: "",
      foI: false,
      foI2: false,
      refweight: "",
      refheight: "",
      refoccupationCode: "",
      refrelationToAppnt: "",
      refposition: "",
      inputAlign: "right",
      popConfig: {
        list: [],
      },
      showPop: false, //弹出框显示
      showSheet: false, //选择sheet显示
      minDate: "", //开始日期
      maxDate: "", //结束日期
      keyWord: "", //关键字查询
      currentDate: "",
    };
  },
  computed: {
    ...mapGetters({
      sexList: "dictionary/sexList",
      nationList: "dictionary/nationList",
      socialSecList: "dictionary/socialSecList",
      crsIdTypeList: "dictionary/crsIdTypeList",
      detailAddrRule: "dictionary/detailAddrRule",
      inputReg: "infoReg/inputReg",
      longTime: "dictionary/longTime",
      idType3ValidFixed: "dictionary/idType3ValidFixed",
      idType11ValidFixed: "dictionary/idType11ValidFixed",
      levelName: "dictionary/ocuuClassName",
      applicant: "insert/applicant",
      assuredList: "insert/assuredList",
      socialName: "page/socialName",
      idImgNotCheck: "page/idImgNotCheck",
    }),
    ageVal() {
      if (this.userInfo.birthDate) {
        const uage = this.$GlobalFuns.userAge(this.userInfo.birthDate);
        this.changeData({
          age: uage,
        });
        return uage;
      } else {
        return "";
      }
    },
    // 邮箱后缀自动补全---待使用
    emails() {
      if (!this.userInfo.email) return [];
      if (this.userInfo.email.indexOf("@") > -1) {
        this.showEmailAppend = false;
        return [];
      }
      let demoEmails = [
          "@qq.com",
          "@139.com",
          "@163.com",
          "@189.cn",
          "@hotmail.com",
          "@sina.com",
          "@wo.com.cn",
          "@gmail.com",
          "@sohu.com",
          "@yahoo.com",
        ],
        arr = [];
      demoEmails.forEach((ele) => {
        arr.push(this.userInfo.email + ele);
      });
      return arr;
    },
    // 便于同时监听证件类型和证件号的变化
    idTypeNum() {
      return this.userInfo.idNum + this.userInfo.idName;
    },
    /**影响证件有效期的参数 */
    relatDateEnd() {
      return (
        this.userInfo.idNum + this.userInfo.idName + this.userInfo.birthDate
      );
    },
    cpCompute: {
      get: function () {
        if (this.foI) {
          return this.userInfo.idNum;
        }
        return idNumFormat(this.userInfo.idNum);
      },
      set: function (val) {
        this.changeData({
          idNum: val.toUpperCase(),
        });
        // this.userInfo.idNum = val.toUpperCase()//转大小写的方法
      },
    },
    cpPhoneNum: {
      get: function () {
        if (this.foI2) {
          return this.userInfo.phone;
        }
        return tellPhoneFormat(this.userInfo.phone);
      },
      set: function (val) {
        this.changeData({
          phone: val.replace(/\s*/g, ""),
        });
      },
    },
    showLonger() {
      let flag = true;
      if (this.ageVal <= 45 && this.userInfo.idType == "0") {
        flag = false;
      }
      // 临时身份证  台湾居民来往大陆通行证最多10年  港澳台居民居住证最多5年  外国人永久居留证最多10年   港澳居民来往内地通行证最多10年  护照无长期
      if (
        ["17", "23", "20", "16", "21", "1"].indexOf(this.userInfo.idType) !== -1
      ) {
        flag = false;
      }
      if (
        (this.userInfo.idType == "3" && this.idType3ValidFixed !== -1) ||
        (this.userInfo.idType == "11" && this.idType11ValidFixed !== -1)
      ) {
        flag = false;
      }
      return flag;
    },
    disabledSex() {
      let res = false;
      const disArr = ["0", "3", "20", "29", "8"];
      if (disArr.includes(`${this.userInfo.idType}`)) {
        res = true;
      }
      return res;
    },
    viewOptions() {
      return this.popConfig.list.filter(
        (item) => item.text.indexOf(this.keyWord) !== -1
      );
    },
    showFrontImg() {
      let res = false;
      if (this.infoReg.hasOwnProperty("frontImg")) {
        res = true;
      }
      if (this.idImgNotCheck.includes(this.userInfo.idType)) {
        res = false;
      }
      return res;
    },
  },
  watch: {
    idTypeNum(val) {
      /**
       *  监听证件类型&证件号
       * 如果是0身份证和3户口本，29港澳 8台居民居住证 计算出生日期 和性别
       */
      if (
        this.disabledSex &&
        this.userInfo.idNum &&
        this.userInfo.idNum.length == 18
      ) {
        this.GetBirthday();
      }
    },
    relatDateEnd() {
      this.validDateDisabled = false;
      if (
        (this.userInfo.idType == "3" && this.idType3ValidFixed !== -1) ||
        (this.userInfo.idType == "11" && this.idType11ValidFixed !== -1)
      ) {
        // console.log(this.idType11ValidFixed, this.userInfo.idType)
        if (this.userInfo.idType == "3" && this.userInfo.idNum.length == 18) {
          if (this.idType3ValidFixed == 1) {
            this.getValidEnd(16, -1); // 证件有效期止期为 16周岁前一天
          } else if (this.idType3ValidFixed == 2) {
            this.getValidEnd(16, 0); // 出生日期+16
          } else if (this.idType3ValidFixed == 9999) {
            this.setValidEnd("长期");
          }
        }
        // 出生证时-首位英文字母+9位阿拉伯数字
        if (this.userInfo.idType == "11" && this.userInfo.idNum.length == 10) {
          if (this.idType11ValidFixed == 1) {
            this.getValidEnd(3, -1); // 证件有效期止期为 3周岁前一天
          } else if (this.idType11ValidFixed == 2) {
            this.getValidEnd(2, 0); // 出生日期+2
          } else if (this.idType11ValidFixed == 3) {
            this.getValidEnd(3, 0); // 出生日期+3
          } else if (this.idType11ValidFixed == 4) {
            this.getValidEnd(4, -1); // 证件有效期止期为4周岁前一天
          } else if (this.idType11ValidFixed == 9999) {
            this.setValidEnd("长期");
          }
        }
      }
    },
    // 身份证类型文字获取
    "userInfo.idType": {
      handler: function (val) {
        if (!this.infoReg.hasOwnProperty("idType")) return;
        if (val) {
          const fdObj = this.idTypeList.find((ele) => ele.keyId == val);
          if (fdObj) {
            if (fdObj.text !== this.userInfo.idName) {
              this.userInfo.idName = fdObj.text;
            }
          } else {
            this.userInfo.idName = "";
            this.userInfo.idType = "";
          }
        } else {
          this.userInfo.idName = "";
        }
      },
    },
    "userInfo.birthDate": {
      handler: function (val) {
        if (val) {
          this.changeData({
            age: this.$GlobalFuns.userAge(val),
          });
        }
      },
    },
  },
  mounted() {},
  methods: {
    formatter(value) {
      if (value === null || value === undefined) return "";
      // 将 value 转换为字符串
      value = String(value);
      return value.replace(/\D/g, "");
    },
    validInfo(str) {
      let res = {
        status: true,
        breakTips: "",
        msg: "",
        target: "",
      };
      if (str == "name") {
        if (!this.userInfo.name) return;
        res = nameRuleCheck(this.userInfo.name, this.userType);
      } else if (str == "idNum") {
        this.watchIdTypeNum();
        if (!this.userInfo.idNum) return;
        res = idNumCheck(this.userInfo, this.userType);
      } else if (str == "emial") {
        if (!this.userInfo.emial) return;
        res = emailCheck(this.userInfo, this.userType);
      } else if (str == "address") {
        if (!this.userInfo.permanentAddress) return;
        res = addrCheck(this.userInfo, this.userType, "permanentAddress");
      }
      let message = res.breakTips || res.msg;
      if (res.status === false) {
        let id = "ref" + res.target;
        this[id] = res.msg;
      }
      if (message) {
        this.$toast(message);
      }
    },
    initDefaultData() {
      // 给switch类型赋值
      if (
        this.infoReg.hasOwnProperty("socialInsuFlag") &&
        !this.userInfo.socialInsuFlag
      ) {
        this.userInfo.socialInsuFlag = "Y";
      }
      // 给证件类型的赋值
      if (this.infoReg.hasOwnProperty("idType") && !this.userInfo.idType) {
        if (this.idTypeList.length > 0) {
          let target = this.idTypeList[0];
          this.changeData({
            idType: target.keyId,
            idName: target.text,
          });
        }
      }
      // 国籍
      if (
        this.infoReg.hasOwnProperty("nationality") &&
        !this.userInfo.nationality
      ) {
        if (this.nationList.length > 0) {
          const fd_chn = this.nationList.find((e) => e.keyId == "CHN");
          let gjObj = {};
          if (fd_chn) {
            gjObj.nationality = fd_chn.keyId;
            gjObj.nationalityName = fd_chn.text;
          } else {
            gjObj.nationality = this.nationList[0].keyId;
            gjObj.nationalityName = this.nationList[0].text;
          }
          this.changeData(gjObj);
        }
      }
      // 投保关系
      if (
        this.infoReg.hasOwnProperty("relationToAppnt") &&
        this.userInfo.relationToAppnt == "4"
      ) {
        this.changeData({
          relationToAppnt: "4",
          relationToAppntName: "本人",
        });
      }
    },
    sureOcrRes(data) {
      // console.log("sureOcrRes---", data);
      if (!data) {
        this.showSheet = false;
        return;
      }
      // 提交图片前,校验证件号
      let res = {
        breakTips: "",
        msg: "",
      };
      if (data.idNum && this.userInfo.idType == "0") {
        res = idNumCheck(data, this.userType);
      }
      let message = res.breakTips || res.msg;
      if (message) {
        return this.$toast(message);
      }
      if (data) {
        if (data.name) {
          this.changeData({
            name: data.name,
          });
        }
        if (data.sex) {
          this.changeData({
            sex: data.sex,
          });
        }
        if (data.sexName) {
          this.changeData({
            sexName: data.sexName,
          });
        }
        if (data.validDate) {
          this.changeData({
            validDate: data.validDate,
          });
        }
        if (data.validDateEnd) {
          this.changeData({
            validDateEnd: data.validDateEnd,
          });
          this.refvalidDateEnd = "";
        }
        if (data.idNum) {
          this.changeData({
            idNum: data.idNum,
          });
        }
        if (data.birthDate) {
          this.changeData({
            birthDate: data.birthDate,
          });
        }
        if (data.zPicUrl) {
          this.changeData({
            frontImg: data.zPicUrl,
          });
        }
        if (data.fPicUrl) {
          this.changeData({
            backImg: data.fPicUrl,
          });
        }
      }
      this.tipsInfo.frontImg = "";
      this.showSheet = false;
    },
    hideAppend() {
      setTimeout(() => {
        this.showEmailAppend = false;
      }, 30);
    },
    changeData(data) {
      Object.assign(this.userInfo, data);
      this.$forceUpdate();
    },
    GetBirthday() {
      const idNum = this.userInfo.idNum,
        birthDate = `${idNum.substring(6, 10)}-${idNum.substring(
          10,
          12
        )}-${idNum.substring(12, 14)}`;
      let xbnum = idNum.substring(16, 17);
      this.changeData({
        sex: xbnum % 2 === 0 ? "1" : "0",
        sexName: xbnum % 2 === 0 ? "女" : "男",
        birthDate: birthDate,
      });
    },
    /**
     * 计算出生日期+age+day 的日期
     * @param {*} age 周岁
     * @param {*} day 天数
     */
    getValidEnd(age, day) {
      // console.log("计算出生日期", age, day)
      if (!this.userInfo.birthDate) return;
      this.userInfo.validDateEnd = countYearDayForAge(
        this.userInfo.birthDate,
        age,
        day
      );
      // 不设置禁止选择
      // this.validDateDisabled = true;
    },
    setValidEnd() {
      this.userInfo.validDateEnd = this.longTime;
      this.validDateDisabled = true;
    },
    // 长期有效
    sameToLongTime(value) {
      let val = this.longTime;
      if (value) {
        //
        if (value.keyId) {
          // 非长期
          val = "";
        }
      } else {
        if (this.userInfo.validDateEnd == this.longTime) {
          val = "";
        }
      }
      this.changeData({
        validDateEnd: val,
      });
    },
    /**
     * 性别确认
     */
    changeSexClick(val) {
      if (
        this.userInfo.idType == "0" ||
        this.userInfo.idType == "3" ||
        this.userInfo.idType == "20"
      ) {
        return;
      }
      this.changeData({
        sex: val.keyId,
      });
    },
    // 日期确认
    onConfirmDate(val) {
      let date = dateToString(val);
      this.changeData({
        [this.popConfig.key]: date,
      });
      this.showPop = false;
    },
    // 职业确认
    onConfirmDJob(val) {
      const str1 = val.accClass,
        str2 = this.levelName || "类",
        leiming = str1 !== void 0 && str1 !== "" ? `(${str1}${str2})` : "";
      // console.log('onConfirmDJob---', val);
      this.changeData({
        occupationCode: val.value,
        occupationCodeName: val.name + `${leiming}`,
        occupationClass: val.accClass,
      });
    },
    changeRadioInfo(obj, key) {
      if (key == "socialInsuFlag") {
        this.changeData({
          socialInsuFlag: obj.keyId,
          socialInsuFlagName: obj.text,
        });
      }
    },
    // 地址确认
    addresssConfirm(value) {
      if (this.popConfig.key == "areaName") {
        this.changeData({
          province: value.provinceCode,
          provinceName: value.provinceName,
          city: value.cityCode,
          cityName: value.cityName,
          county: value.countyCode,
          countyName: value.countyName,
          areaName: value.addressDetail, //通讯地址 省+市+县
          zipCode: value.zipCode,
          townName: value.townName || "",
          townNo: value.townNo || "",
          town: value.townNo || "", // 新接口townNo改为town
        });
      }
      this.showPop = false;
    },
    watchIdTypeNum() {
      if (!this.infoReg.hasOwnProperty("healthyStatus")) return;
      this.watchNstatus();
    },
    /**
     * 弹出框确定
     * @param {*} val
     */
    onConfirmPick(val) {
      if (this.popConfig.key == "idType") {
        this.changeData({
          idType: val.keyId,
          idName: val.text,
        });
        if (
          this.disabledSex &&
          this.userInfo.idNum &&
          this.userInfo.idNum.length == 18
        ) {
          this.GetBirthday();
        }
        this.watchIdTypeNum();
      } else if (this.popConfig.key == "holderType") {
        this.changeData({
          holderType: val.keyId,
          holderTypeName: val.text,
        });
      } else if (this.popConfig.key == "sex") {
        this.changeData({
          sex: val.keyId,
          sexName: val.text,
        });
      } else if (this.popConfig.key == "crsIdType") {
        this.changeData({
          crsIdType: val.keyId,
          crsIdTypeName: val.text,
        });
      } else if (this.popConfig.key == "relationToAppnt") {
        this.changeData({
          relationToAppnt: val.keyId,
          relationToAppntName: val.text,
        });
      }else if (this.popConfig.key == "nationality") {
        this.changeData({
          nationality: val.keyId,
          nationalityName: val.text,
        });
      }
      this.showPop = false;
    },
    /**
     * 打开弹出框
     */
    showPopAction(type, key, list, curVal = "") {
      this.defaultIndex = 0;
      if (this.disabledEdit) return;
      if (key == "birthDate") {
        if (["0", "3", "20"].includes(this.userInfo.idType)) {
          return;
        }
      } else if (key == "validDateEnd") {
        if (this.validDateDisabled) return;
      }
      this.popConfig = {
        type,
        key,
        list,
      };
      if (list.length == 1) {
        // 只有一条默认当前值
        this.onConfirmPick(list[0]);
        return;
      }
      if (type == "date") {
        this.currentDate = new Date();
        if (key == "birthDate") {
          this.minDate = this.tbBirthStrMin;
          this.maxDate = this.tbBirthStrMax;
          if (this.userInfo.birthDate) {
            this.currentDate = new Date(
              this.userInfo.birthDate.replace(/-/g, "/")
            );
          }
        } else if (key == "validDate") {
          this.minDate = new Date("1970/10/11");
          this.maxDate = new Date();
          if (this.userInfo.validDate) {
            this.currentDate = new Date(
              this.userInfo.validDate.replace(/-/g, "/")
            );
          }
        } else if (key == "validDateEnd") {
          this.minDate = new Date();
          this.maxDate = new Date("2060/10/11");
          if (this.userInfo.validDateEnd) {
            this.currentDate = new Date(
              this.userInfo.validDateEnd.replace(/-/g, "/")
            );
          }
        } else {
          this.minDate = new Date("2020/10/11");
          this.maxDate = new Date("2090/10/1");
        }
      }
      if (list.length > 0) {
        let defaultIndex = list.findIndex(
          (item) => curVal == item.keyId || item.default
        );
        if (defaultIndex > 0) {
          this.defaultIndex = defaultIndex;
        }
      }
      // console.log(this.currentDate)
      this.$nextTick(() => {
        this.showPop = true;
      });
    },
    openCrsIdType() {
      this.showPopAction("picker", "crsIdType", this.crsIdTypeList);
    },
    /* === 验证码 === */
    async checkSmsCode() {
      if (!this.userInfo.validCode) {
        this.$toast("请输入短信验证码");
        return { status: false };
      }
      // 校验短信验证码
      this.$store.commit("updateLoad", true);
      let res = await checkPhoneSmsCode(
        this.userInfo.phone,
        this.userInfo.validCode
      );
      this.$store.commit("updateLoad", false);
      if (res.code == 1) {
        this.changeData({
          validCode: this.userInfo.validCode,
        });
        return { status: true };
      } else {
        this.$baseAlert("短信验证码校验失败，请确认手机号和验证码是否匹配");
        return { status: false };
      }
    },
    goBackTop() {
      this.$backRouter();
    },
  },
};

export const bbrAndSyrInfoMix = {
  computed: {
    tbrWholeAddr() {
      return `${this.applicant.areaName || ""}${
        this.applicant.permanentAddress || ""
      }`;
    },
    bbrWholeAddr() {
      return `${this.userInfo.areaName || ""}${
        this.userInfo.permanentAddress || ""
      }`;
    },
    sameAppntForAreaAddr() {
      return this.bbrWholeAddr === this.tbrWholeAddr;
    },
    sameAppntForEmail() {
      return this.userInfo.email === this.applicant.email;
    },
    sameAppntForPhone() {
      return this.userInfo.phone === this.applicant.phone;
    },
  },
  methods: {
    sameToAppnt(event, type) {
      if (event) event.preventDefault();
      if (type == "areaName") {
        let obj = {
          city: "",
          cityName: "",
          county: "",
          countyName: "",
          areaName: "",
          province: "",
          provinceName: "",
          permanentAddress: "",
        };
        if (!this.sameAppntForAreaAddr) {
          obj = {
            city: this.applicant.city || "",
            cityName: this.applicant.cityName || "",
            county: this.applicant.county || "",
            countyName: this.applicant.countyName || "",
            areaName: this.applicant.areaName || "",
            province: this.applicant.province || "",
            provinceName: this.applicant.provinceName || "",
            zipCode: this.applicant.zipCode || "",
            permanentAddress: this.applicant.permanentAddress || "",
          };
        }
        this.changeData(obj);
      } else if (type == "email") {
        this.changeData({
          email: !this.sameAppntForEmail ? this.applicant.email : "",
        });
      } else if (type == "phone") {
        this.changeData({
          phone: !this.sameAppntForPhone ? this.applicant.phone : "",
        });
      }
    },
  },
};
